package Login.Service;

import Login.entity.Book;
import Login.util.ConnectMySql;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class BookService {
    ConnectMySql connectMySql = new ConnectMySql();
    HttpSession session;

    public boolean hasSession(HttpSession session, HttpServletResponse response) throws IOException {
        if (session.isNew() || session.getAttribute("user")==null) {
            response.sendRedirect("login.jsp");
            return false;
        }
        return true;
    }

    public ArrayList<Book> getBookList() throws SQLException {
        ArrayList<Book> list=new ArrayList<>();
        connectMySql.openMySql();
        String sql = "select * from test.Book";
        ResultSet resultSet = connectMySql.select(sql);
        while (resultSet.next()) {
            Book book = new Book();
            book.setBookId(resultSet.getString("bookId"));
            book.setBookName(resultSet.getString("bookName"));
            book.setBookStatus(resultSet.getString("bookStatus"));
            list.add(book);
        }
        connectMySql.closeMySql();
        return list;
    }

    public Book getBook(String id) throws SQLException {
        connectMySql.openMySql();
        String sql = "select * from test.Book where bookId='"+id+"'";
        System.out.println(sql);
        ResultSet resultSet = connectMySql.select(sql);
        ArrayList<Book> list=new ArrayList<>();
        while (resultSet.next()) {
            Book book = new Book();
            book.setBookId(resultSet.getString("bookId"));
            book.setBookName(resultSet.getString("bookName"));
            book.setBookStatus(resultSet.getString("bookStatus"));
            list.add(book);
        }
        connectMySql.closeMySql();
        Book book = list.get(0);
        return book;
    }

    public int addBook(Book book) {
        connectMySql.openMySql();
        String sql = "insert into test.Book (bookId, bookName, bookStatus) values ('"+book.getBookId()+"','"+book.getBookName()+"','"+book.getBookStatus()+"')";
        int ret = connectMySql.update(sql);
        connectMySql.closeMySql();
        return ret;
    }

    public int delBook(String bookId) {
        connectMySql.openMySql();
        String sql = "delete from test.Book where bookId='"+bookId+"'";
        int del = connectMySql.update(sql);
        connectMySql.closeMySql();
        return del;
    }

    public int update(Book book) {
        connectMySql.openMySql();
        String sql = "update test.Book set bookName='"+book.getBookName()+"', bookStatus='"+book.getBookStatus()+"' where bookId='"+book.getBookId()+"'";
        int update = connectMySql.update(sql);
        return update;
    }
}
